package id.co.rho.scoring.cid.changecontrol;

import id.co.rho.scoring.cid.changecontrol.entitychange.UpdateEntityChange;
import id.co.rho.scoring.cid.changecontrol.entitychange.propertychange.PropertyChange;

import java.lang.reflect.Method;
import java.util.List;

import javax.persistence.EntityManager;



public class UpdateChangeCommand implements ChangeControl {

	EntityManager entityManager;
	UpdateEntityChange entityChange;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public UpdateEntityChange getEntityChange() {
		return entityChange;
	}



	public void setEntityChange(UpdateEntityChange entityChange) {
		this.entityChange = entityChange;
	}



//	@Override
	public void execute() {
		try {
			Object persistentEntity = entityManager.find(
					Class.forName(entityChange.getEntityType()),
					entityChange.getEntityId());

			List<PropertyChange> propChanges = entityChange.getPropertyChanges();
			if (propChanges.size() != 0) {
				for (int i = 0; i < propChanges.size(); i++) {
					apply(persistentEntity, propChanges.get(i)
							.getPropertyName(), propChanges.get(i)
							.getNewValue());

				}
			}
			entityManager.merge(persistentEntity);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void apply(Object entityDb, String fieldName, Object newValue) {
		try {
			Method setter = getSetterMethod(entityDb.getClass(), fieldName);
			if (entityDb != null)
				setter.invoke(entityDb, newValue);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static Method getSetterMethod(Class entityClazz, String fieldName) {
		fieldName = fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1); // uppercase first letter
		final String setterName = "set" + fieldName;
		Method m;
		for (int i = 0; i < entityClazz.getMethods().length; i++) {
			m = entityClazz.getMethods()[i];
			if (m.getName().equals(setterName) && m.getParameterTypes() != null
					&& m.getParameterTypes().length == 1) {
				return m;
			}
		}
		return null;
	}

	@Override
	public void executeInsertChange() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void executeUpdateChange() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void executeDeleteChange() {
		// TODO Auto-generated method stub
		
	}
}
